﻿using System.Diagnostics;
using System.IO;
using ClosedXML.Excel;
using Haimen.Excel;
using Microsoft.Office.Interop.Excel;

namespace Haimen.Func1;

internal class ResultInputFiller(
    ExcelFileUtils excelUtil) {

  public void Fill(AppEnvPath path, string[] groupList) {
    string resultTpl = ResolveResultTemplate(path, groupList);
    string resultPath = path.OutDir("数据分析表.xlsx");
    File.Copy(resultTpl, resultPath, overwrite: true);

    string mergeOut = path.OutDir(path.Merge);
    Application excelApp = new() {
      Visible = true,
      ScreenUpdating = false,
    };

    var OpenBook = (string path) => {
      Debug.Assert(File.Exists(path));
      return excelApp.Workbooks.Open(path);
    };

    Workbook resultBook = OpenBook(resultPath);
    Workbook mergeBook = OpenBook(mergeOut);

    foreach (string sheetName in groupList) {
      Worksheet fromSheet = mergeBook.Sheets[sheetName];
      Worksheet toSheet = resultBook.Sheets[sheetName];
      CopySheet(fromSheet, toSheet, "A1");
    }

    mergeBook.Activate();
    excelApp.CutCopyMode = 0;
    mergeBook.Close();

    resultBook.Save();
    resultBook.Close();
    excelApp.Quit();
  }

  string ResolveResultTemplate(AppEnvPath path, string[] groups) {
    const string result = "result.xlsx";
    string dev = path.InDev(result);
    if (!File.Exists(dev)) {
      return path.ResFunc1(result);
    }

    System.Console.WriteLine($"检测到dev：{dev}");
    using FileStream stream = _excelUtil.OpenRead(dev);
    using XLWorkbook resultBook = new(stream);

    foreach (string group in groups) {
      IXLWorksheet sheet = resultBook.Worksheet(group);
      int rowCount = sheet.LastRowUsed().RowNumber();

      //TODO: 直接帮删
      if (rowCount != 2) {
        throw new System.Exception(
          $"结果模板数据源只允许存在一行！(Sheet：{group}，总行数：{rowCount})");
      }
    }

    return dev;
  }

  void CopySheet(Worksheet fromSheet, Worksheet toSheet, string toCell) {
    fromSheet.Activate();

    Range lastCell = fromSheet.Cells.SpecialCells(XlCellType.xlCellTypeLastCell);
    Range all = fromSheet.Range[fromSheet.Cells[1, 1], lastCell];
    //Range all = fromSheet.Range["A1:H3"];
    int rowCount = all.Rows.Count;
    //System.Console.WriteLine("------------- " + rowCount);
    all.Select();
    all.Copy();

    Range target = toSheet.Range[toCell];
    toSheet.Activate();
    target.Select();
    toSheet.Paste();

    // 删除范围外多余的行
    DeleteBelow(toSheet, target.Row + rowCount);
  }

  void DeleteBelow(Worksheet sheet, int delStart) {
    int delEnd = sheet.Cells.SpecialCells(XlCellType.xlCellTypeLastCell).Row;
    if (delStart > delEnd) {
      return;
    }

    //System.Console.WriteLine($"***---------- {delStart} {delEnd}");
    Range delRange = sheet.Rows[$"{delStart}:{delEnd}"];
    delRange.Select();
    delRange.Delete();

    sheet.Cells[delStart, 1].Select();
  }

  readonly ExcelFileUtils _excelUtil = excelUtil;
}
